package com.base.component.ai.workflow.handle;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.function.Consumer;

import org.springframework.stereotype.Component;

import com.base.component.ai.agent.bo.ContextBO;
import com.base.component.ai.agent.bo.ContextParamBO;
import com.base.component.ai.workflow.core.NodeHandle;
import com.base.component.ai.workflow.core.NodeTypeEnum;
import com.base.component.ai.workflow.flow.Flow;
import com.base.component.ai.workflow.logs.NodeLog;
import com.base.component.ai.workflow.logs.NodeLogConidition;
import com.base.component.ai.workflow.node.Node;
import com.base.component.ai.workflow.node.NodeCondition;
import com.gitee.magic.core.json.JsonObject;
import com.greenpineyu.fel.FelEngine;
import com.greenpineyu.fel.FelEngineImpl;
import com.greenpineyu.fel.context.FelContext;

@Component
public class NodeHandleCondition<MSG,AP extends ContextParamBO,PP> implements NodeHandle<MSG,AP,PP>{

	@Override
	public <T extends Node> boolean support(Class<T> cls) {
		return cls.equals(NodeCondition.class);
	}

	@Override
	public <T extends Node>List<Flow> execute(ContextBO<MSG,AP,PP> context,Map<String,Object> params,Flow flow,T node,Consumer<NodeLog> c) {
		NodeCondition d=(NodeCondition)node;
		FelEngine felEngine = new FelEngineImpl();
		FelContext felContext = felEngine.getContext();
		for(String key:params.keySet()) {
			felContext.set(key,params.get(key));
		}
		for(String expression:d.getExpression().keySet()) {
			boolean match = (boolean) felEngine.eval(expression, felContext);
			if(match) {
				List<Flow> flows= d.getExpression().get(expression);
				List<NodeTypeEnum> nodeTypes=new ArrayList<>();
				for(Flow f:flows) {
					nodeTypes.add(f.getNode().getNodeType());
				}
				NodeLogConidition nodeLog=new NodeLogConidition();
				nodeLog.setExpression(expression);
				nodeLog.setNodeTypes(nodeTypes);
				c.accept(nodeLog);
				return flows;
			}
		}
		List<NodeTypeEnum> nodeTypes=new ArrayList<>();
		for(Flow f:flow.getNexts()) {
			nodeTypes.add(f.getNode().getNodeType());
		}
		NodeLogConidition nodeLog=new NodeLogConidition();
		nodeLog.setNodeTypes(nodeTypes);
		c.accept(nodeLog);
		return flow.getNexts();
	}

	
	public static void main(String[] args) {
		JsonObject json=new JsonObject();
		json.put("name", "魏振耀");
		json.put("assetRecover",false);
		
		FelEngine fel = new FelEngineImpl();    
		FelContext felContext = fel.getContext();
		felContext.set("dddaa", json);
		
		System.out.println(fel.eval("dddaa.name"));
		System.out.println(fel.eval("dddaa.assetRecover"));   
	}
	
}
